<?php

namespace Dcat\Admin\Grid\Displayers;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Facades\Storage;

class Preview extends AbstractDisplayer
{

    public function display($disk = '', $server = '', $width = 200, $height = 200)
    {
        if ($this->value instanceof Arrayable) {
            $this->value = $this->value->toArray();
        }

        return collect((array)$this->value)->filter()->map(function ($path) use ($disk, $server, $width, $height) {
            // 生成缩略图路径和原图路径
            $thumbnailSrc = $this->generateThumbnailPath($path, $disk, $server);
            $originalSrc = $this->generateOriginalPath($path, $disk, $server);

            // 获取文件扩展名并转为小写
            $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            $imageExtensions = ['jpg', 'jpeg', 'tiff', 'bmp', 'png'];

            if (in_array($extension, $imageExtensions)) {
                return "<img
                    data-action='preview-img'
                    src='{$thumbnailSrc}'
                    data-original-src='{$originalSrc}'
                    style='max-width:{$width}px;max-height:{$height}px;cursor:pointer'
                    class='img img-thumbnail'
                />";
            } else {
                return "<a href='{$originalSrc}' download>
                    {$thumbnailSrc}
                </a>";
            }
        })->implode('&nbsp;');
    }

    /**
     * 生成缩略图路径
     */
    private function generateThumbnailPath($path, $disk = '', $server = '')
    {
        // 获取文件扩展名并转为小写
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));

        // 支持的图片格式
        $imageExtensions = config('admin.icons.image_icon');

        if (in_array($extension, $imageExtensions)) {
            // 图片文件按新逻辑生成缩略图路径
            if (url()->isValidUrl($path) || mb_strpos($path, 'data:image') === 0) {
                return $path;
            }
            // 获取文件所在目录
            $directory = pathinfo($path, PATHINFO_DIRNAME);
            // 获取文件名（不包含扩展名）
            $filename = pathinfo($path, PATHINFO_FILENAME);
            // 构建缩略图文件名
            $thumbnailFilename = $filename . '-thumbnail.' . $extension;
            // 构建缩略图所在的目录
            $thumbnailDirectory = $directory . '/other/thumb';
            // 构建缩略图完整路径
            $thumbnailPath = $thumbnailDirectory . '/' . $thumbnailFilename;

            if ($server) {
                $fullThumbnailPath = rtrim($server, '/') . '/' . ltrim($thumbnailPath, '/');
            } else {
                if ($disk) {
                    $fullThumbnailPath = Storage::disk($disk)->url($thumbnailPath);
                } else {
                    $fullThumbnailPath = Storage::disk(config('admin.upload.disk'))->url($thumbnailPath);
                }
            }

            // 检查缩略图文件是否存在
            if ($server) {
                $localThumbnailPath = rtrim($server, '/') . '/' . ltrim($thumbnailPath, '/');
            } else {
                if ($disk) {
                    $localThumbnailPath = Storage::disk($disk)->path($thumbnailPath);
                } else {
                    $localThumbnailPath = Storage::disk(config('admin.upload.disk'))->path($thumbnailPath);
                }
            }

            if (file_exists($localThumbnailPath)) {
                return $fullThumbnailPath;
            } else {
                return $this->generateOriginalPath($path, $disk, $server);
            }
        } else {
            // 非图片文件返回固定图标路径
            return $this->getFixedIconPath($extension);
        }
    }

    /**
     * 获取固定文件类型图标路径
     */
    private function getFixedIconPath($extension)
    {
        $icons = config('admin.icons');
        // 初始化一个空数组用于存储合并后的结果
        $mergedIcons = [];

        // 遍历 $icons 数组，跳过 'image_icon'
        foreach ($icons as $category => $iconArray) {
            if ($category !== 'image_icon') {
                $mergedIcons = array_merge($mergedIcons, $iconArray);
            }
        }
        return $mergedIcons[$extension] ?? $mergedIcons['default'];
    }

    /**
     * 生成原图路径（保持不变）
     */
    private function generateOriginalPath($path, $disk = '', $server = '')
    {
        if (url()->isValidUrl($path) || mb_strpos($path, 'data:image') === 0) {
            return $path;
        } elseif ($server) {
            return rtrim($server, '/') . '/' . ltrim($path, '/');
        } else {
            if ($disk) {
                return Storage::disk($disk)->url($path);
            } else {
                return Storage::disk(config('admin.upload.disk'))->url($path);
            }
        }
    }
}
